<template>
  <Card title="嵌套表" :head-style="{ textAlign: 'center', fontWeight: 'bold' }">
    <div class="w-full flex">
      <div></div>
      <BasicForm @register="registerForm">
        <template #imgComb>
          <div>
            <RadioGroup
              v-model:value="dataRef.comb"
              button-style="solid"
              @change="handleChangeComb"
            >
              <template v-for="item in tjList" :key="`${item.value}`">
                <RadioButton :value="item.value">
                  {{ item.label }}
                </RadioButton>
              </template>
            </RadioGroup>
            <div class="mt-2" v-if="dataRef.comb == 1">
              <a-button
                style="margin: 10px 0"
                :type="dataRef.filter && dataRef.filter.length ? 'primary' : 'default'"
                @click="handleConfiguration"
              >
                配置
              </a-button>
            </div>
            <NestTableFormDesign
              v-if="dataRef.comb == 2"
              class="mt-2"
              v-model:modelValue="dataRef.conds"
              :formGetFieldsData="formGetFieldsData"
            />
          </div>
        </template>
        <template #queryName>
          <div>
            <span>{{ dataRef.queryName || '' }}</span>
            <a-button type="link" @click="handleSlectSearch" class="ml-5">请选择查询</a-button>
          </div>
        </template>
      </BasicForm>
    </div>
    <NestTableFormConfigationModal
      @register="registerNestTableFormConfigationModal"
      @success="handleSuccessNestTableFormConfigationModal"
    />
    <SelectSearchDataModal
      @register="registerSelectSearchDataModal"
      @success="handleSuccessSelectSearchDataModal"
    />
  </Card>
</template>
<script lang="ts" setup>
  import { ref, PropType, unref, watch, onMounted, computed, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Card, Radio, message } from 'ant-design-vue';
  import { FormSchema } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { NestTableFormConfigationModal } from './nestTableFormConfigation';
  import { NestTableFormDesign } from './nestTableFormDesign';
  import { SelectSearchDataModal } from './selectSearchData';
  import { getVisualListModule } from '/@/api/formDesign/formDesign';
  const RadioGroup = Radio.Group;
  const RadioButton = Radio.Button;

  const emit = defineEmits([
    'update:modelValue',
    'moduleChangeLeft',
    'moduleChangeRight',
    'setQueryId',
  ]);
  const props = defineProps({
    modelValue: {
      type: Object as PropType<Object>,
      default: () => {
        return {};
      },
    },
    type: {
      type: String as PropType<String>,
      default: '1',
    },
    formGetFieldsData: {
      type: Array,
      default: () => [],
    },
  });
  const dataRef = ref<Recordable>({});
  const optionsList = ref([]);
  // watch(
  //   () => props.modelValue,
  //   async (newVal) => {
  //     await nextTick();
  //     dataRef.value = newVal;
  //     if (!dataRef.value.comb) {
  //       dataRef.value.comb = '1';
  //     }
  //     resetFields();
  //     setFieldsValue({
  //       ...dataRef.value,
  //     });
  //   },
  //   {
  //     immediate: true,
  //   },
  // );
  const submit = async () => {
    const data = await validate();
    console.log('dataRef.value', dataRef.value);
    dataRef.value = Object.assign({}, dataRef.value, data);
    console.log('dataRef.value2', dataRef.value);
    emit('update:modelValue', dataRef.value);
    return dataRef.value;
  };
  defineExpose({
    submit,
  });
  const formSchema1: FormSchema[] = [
    {
      field: 'forms',
      label: '模块',
      required: true,
      component: 'Select',
      colProps: { span: 12 },
      componentProps: {
        showSearch: true,
        optionFilterProp: 'name',
        options: unref(optionsList),
        fieldNames: { label: 'name', value: 'code' },
        onChange: (e: any) => {
          moduleChangeLeft(e);
        },
      },
    },
    {
      field: 'isSearchable',
      label: '搜索',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
    {
      field: 'isPage',
      label: '分页',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
    {
      field: 'pageSize',
      label: '每页条数',
      required: false,
      component: 'InputNumber',
      colProps: { span: 12 },
      componentProps: {
        defaultValue: 20,
      },
    },
    {
      field: 'selWinUrl',
      label: '显示窗口页面',
      required: false,
      component: 'Input',
      colProps: { span: 12 },
    },
    {
      field: 'isNoShow',
      label: '显示序号',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
      componentProps: {
        defaultValue: true,
      },
    },
    {
      field: 'isTab',
      label: '显示为选项卡',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
      componentProps: {},
    },
  ];
  const formSchema2: FormSchema[] = [
    {
      field: 'forms',
      label: '源模块',
      required: true,
      component: 'Select',
      colProps: { span: 12 },
      componentProps: {
        showSearch: true,
        options: unref(optionsList),
        optionFilterProp: 'name',
        fieldNames: { label: 'name', value: 'code' },
        onChange: (e: any) => {
          moduleChangeLeft(e);
        },
      },
    },
    {
      field: 'destForm',
      label: '嵌套表单',
      required: true,
      component: 'Select',
      colProps: { span: 12 },
      componentProps: {
        showSearch: true,
        options: unref(optionsList),
        optionFilterProp: 'name',
        fieldNames: { label: 'name', value: 'code' },
        onChange: (e: any) => {
          moduleChangeRight(e);
        },
      },
    },
    {
      field: 'isAgainst',
      label: '自动冲抵',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
      ifShow: false,
    },
    {
      field: 'isAutoSel',
      label: '自动拉单',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
    {
      field: 'isAddHighlight',
      label: '新增高亮',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
      helpMessage: '区别于拉单的数据，手工新增的数据高亮显示',
    },
    {
      field: 'isSearchable',
      label: '搜索',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
    {
      field: 'isPage',
      label: '分页',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
    {
      field: 'pageSize',
      label: '每页条数',
      required: false,
      component: 'InputNumber',
      colProps: { span: 12 },
      componentProps: {
        defaultValue: 20,
      },
    },
    {
      field: 'isShowFlow',
      label: '显示引用记录或流程',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
    {
      field: 'isNoShow',
      label: '显示序号',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
      componentProps: {
        defaultValue: true,
      },
    },
    {
      field: 'isTab',
      label: '显示为选项卡',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
    {
      field: 'imgComb',
      label: '过滤条件',
      required: false,
      component: 'Checkbox',
      colProps: { span: 24 },
      slot: 'imgComb',
    },
  ];
  const formSchema3: FormSchema[] = [
    {
      field: 'queryName',
      label: '来源',
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      slot: 'queryName',
    },
    {
      field: 'destForm',
      label: '嵌套表单',
      required: true,
      component: 'Select',
      colProps: { span: 12 },
      componentProps: {
        showSearch: true,
        options: unref(optionsList),
        optionFilterProp: 'name',
        fieldNames: { label: 'name', value: 'code' },
        onChange: (e: any) => {
          moduleChangeRight(e);
        },
      },
    },
    {
      field: 'isPage',
      label: '分页',
      required: false,
      component: 'Checkbox',
      colProps: { span: 12 },
    },
  ];
  const [
    registerForm,
    { resetFields, setFieldsValue, validate, updateSchema, resetSchema, getFieldsValue },
  ] = useForm({
    labelWidth: 150,
    schemas: formSchema1,
    showActionButtonGroup: false,
  });

  onMounted(async () => {
    optionsList.value = await getVisualListModule();
    console.log('modelValue', props.modelValue);
    dataRef.value = props.modelValue;
    if (!dataRef.value.comb) {
      dataRef.value.comb = '1';
    }
    if (props.type == '1') {
      formSchema1[0].componentProps.options = optionsList.value;
      resetSchema(formSchema1);
    } else if (props.type == '2') {
      formSchema2[0].componentProps.options = optionsList.value;
      formSchema2[1].componentProps.options = optionsList.value;
      resetSchema(formSchema2);
    } else if (props.type == '3') {
      formSchema3[1].componentProps.options = optionsList.value;
      resetSchema(formSchema3);
    }
    resetFields();
    // setFieldsValue({ isNoShow: true });
    setFieldsValue({
      ...dataRef.value,
    });
  });

  const tjList = [
    {
      value: '1',
      label: '组合条件',
    },
    {
      value: '2',
      label: '脚本条件',
    },
  ];

  const [registerNestTableFormConfigationModal, { openModal: openConfiguration }] = useModal();
  //组合条件配置
  const handleConfiguration = () => {
    openConfiguration(true, {
      list: dataRef.value.filter || [],
      formGetFieldsData: props.formGetFieldsData,
    });
  };
  //配置回调
  const handleSuccessNestTableFormConfigationModal = (val) => {
    dataRef.value.filter = val;
  };

  const [registerSelectSearchDataModal, { openModal: openSelectSearchDataModal }] = useModal();

  const handleSuccessSelectSearchDataModal = (record) => {
    dataRef.value.queryName = record.queryName;
    dataRef.value.queryId = record.id;
    setFieldsValue({ queryId: dataRef.value.queryId });
    emit('setQueryId', dataRef.value.queryId);
  };
  //选择查询
  const handleSlectSearch = () => {
    openSelectSearchDataModal(true, {});
  };

  //change
  const handleChangeComb = () => {};

  //左侧module改变
  const moduleChangeLeft = (e) => {
    console.log('moduleChangeLeft', e);
    if (e) {
      // const record = getFieldsValue();
      // if (record.destForm == e) {
      //   message.warning('源模块不能和嵌套表单相同');
      //   setFieldsValue({ forms: '' });
      //   return;
      // }
      const model = optionsList.value.filter((item) => item.code == e)[0];
      emit('moduleChangeLeft', e, model);
    } else {
      emit('moduleChangeLeft', e, {});
    }
  };
  //右侧module改变
  const moduleChangeRight = (e) => {
    if (e) {
      const record = getFieldsValue();
      if (record.forms == e) {
        message.warning('嵌套表单不能和源模块相同');
        setFieldsValue({ destForm: '' });
        return;
      }
      const model = optionsList.value.filter((item) => item.code == e)[0];
      emit('moduleChangeRight', e, model);
    } else {
      emit('moduleChangeRight', e, {});
    }
  };
</script>
